const FileService = require('../services/fileService');
const { formatResponse } = require('../utils/transform');

class FileController {
  constructor() {
    this.fileService = new FileService();
  }

  // 上传文件
  async uploadFile(ctx) {
    try {
      // 尝试从不同位置获取文件
      const file = ctx.req.file || ctx.file;

      if (!file) {
        ctx.status = 400;
        ctx.body = formatResponse(400, '请选择文件', null, {
          hasReqFile: !!ctx.req.file,
          hasCtxFile: !!ctx.file,
          hasRequestFiles: !!ctx.request.files
        });
        return;
      }

      console.log('接收到的文件信息:', {
        originalname: file.originalname,
        filename: file.filename,
        path: file.path,
        mimetype: file.mimetype,
        size: file.size
      });

      const result = await this.fileService.uploadFile(file);

      if (result.success) {
        ctx.status = 200;
        ctx.body = formatResponse(200, result.message, result.data);
      } else {
        ctx.status = 500;
        ctx.body = formatResponse(500, result.message, null, { error: result.error });
      }
    } catch (error) {
      console.error('文件上传控制器错误:', error);
      ctx.status = 500;
      ctx.body = formatResponse(500, '上传失败，请稍后重试', null, { error: error.message });
    }
  }

  // 获取文件列表
  async getFileList(ctx) {
    try {
      const result = await this.fileService.getFileList();

      if (result.success) {
        ctx.status = 200;
        ctx.body = formatResponse(200, result.message, result.data);
      } else {
        ctx.status = 500;
        ctx.body = formatResponse(500, result.message, null, { error: result.error });
      }
    } catch (error) {
      console.error('获取文件列表控制器错误:', error);
      ctx.status = 500;
      ctx.body = formatResponse(500, '获取文件列表失败', null, { error: error.message });
    }
  }

  // 删除文件
  async deleteFile(ctx) {
    try {
      const { id } = ctx.params;

      if (!id) {
        ctx.status = 400;
        ctx.body = formatResponse(400, '文件ID不能为空', null);
        return;
      }

      const result = await this.fileService.deleteFile(id);

      if (result.success) {
        ctx.status = 200;
        ctx.body = formatResponse(200, result.message, null);
      } else {
        ctx.status = result.status || 500;
        ctx.body = formatResponse(
          result.status || 500,
          result.message,
          null,
          { error: result.error }
        );
      }
    } catch (error) {
      console.error('删除文件控制器错误:', error);
      ctx.status = 500;
      ctx.body = formatResponse(500, '删除失败', null, { error: error.message });
    }
  }
}

module.exports = FileController;